"""
迭代关联性工具函数
提供增强迭代关联性的辅助函数
"""

from typing import Dict, List, Any, Optional
from datetime import datetime
from src.research_core.project_state import ProjectManagementState

def add_iteration_record(state: ProjectManagementState, 
                        agent_type: str, 
                        result: Dict[str, Any],
                        decision: Optional[str] = None) -> Dict[str, Any]:
    """
    添加迭代记录
    
    Args:
        state: 项目状态
        agent_type: 代理类型
        result: 执行结果
        decision: 决策信息
        
    Returns:
        需要更新的状态字段字典
    """
    # 创建要更新的字段字典
    updates = {}
    
    # 确保必要的字段存在
    iteration_count = state.get("iteration_count", 0)
    iteration_history = state.get("iteration_history", []).copy()
    
    iteration_record = {
        "timestamp": datetime.now().isoformat(),
        "phase": state.get("project_phase", "unknown"),
        "agent_type": agent_type,
        "result": result,
        "decision": decision,
        "iteration_count": iteration_count
    }
    
    iteration_history.append(iteration_record)
    iteration_count += 1
    
    # 只返回需要更新的字段
    updates["iteration_history"] = iteration_history
    updates["iteration_count"] = iteration_count
    
    return updates

def add_decision_record(state: ProjectManagementState, 
                       decision_type: str, 
                       decision_data: Dict[str, Any],
                       reasoning: str) -> Dict[str, Any]:
    """
    添加决策记录
    
    Args:
        state: 项目状态
        decision_type: 决策类型
        decision_data: 决策数据
        reasoning: 决策理由
        
    Returns:
        需要更新的状态字段字典
    """
    # 创建要更新的字段字典
    updates = {}
    
    # 确保必要的字段存在
    decision_history = state.get("decision_history", []).copy()
    iteration_count = state.get("iteration_count", 0)

    decision_record = {
        "timestamp": datetime.now().isoformat(),
        "phase": state.get("project_phase", "unknown"),
        "decision_type": decision_type,
        "decision_data": decision_data,
        "reasoning": reasoning,
        "iteration_count": iteration_count
    }
    
    decision_history.append(decision_record)
    
    # 只返回需要更新的字段
    updates["decision_history"] = decision_history
    
    return updates

def calculate_quality_metrics(state: ProjectManagementState, 
                            current_results: Dict[str, Any]) -> Dict[str, float]:
    """
    计算质量评估指标
    
    Args:
        state: 项目状态
        current_results: 当前执行结果
        
    Returns:
        质量指标字典
    """
    metrics = {}
    
    # 根据阶段计算不同的质量指标
    phase = state.get("project_phase", "requirements")
    
    if phase == "requirements":
        # 需求分析质量指标
        req_analysis = current_results.get("requirements_analysis", {})
        metrics["completeness"] = _calculate_completeness(req_analysis)
        metrics["clarity"] = _calculate_clarity(req_analysis)
        
    elif phase == "design":
        # 设计质量指标
        product_design = current_results.get("product_design", {})
        ui_design = current_results.get("ui_ux_design", {})
        metrics["innovation"] = _calculate_innovation(product_design)
        metrics["usability"] = _calculate_usability(ui_design)
        
    elif phase == "development":
        # 开发质量指标
        code = current_results.get("development_code", "")
        metrics["code_quality"] = _calculate_code_quality(code)
        metrics["modularity"] = _calculate_modularity(code)
        
    elif phase == "testing":
        # 测试质量指标
        test_results = current_results.get("test_results", {})
        metrics["coverage"] = test_results.get("test_coverage", 0)
        metrics["pass_rate"] = test_results.get("pass_rate", 0)
    
    # 更新状态中的质量指标
    if "quality_metrics" not in state:
        state["quality_metrics"] = {}
    state["quality_metrics"].update(metrics)
    return metrics

def get_adaptive_threshold(state: ProjectManagementState, threshold_type: str) -> float:
    """
    获取自适应阈值
    
    Args:
        state: 项目状态
        threshold_type: 阈值类型
        
    Returns:
        自适应阈值
    """
    # 默认阈值
    default_thresholds = {
        "test_pass_rate": 0.8,
        "quality_score": 0.7,
        "feedback_approval": 0.6
    }
    
    # 如果有自定义阈值，使用自定义值
    adaptive_thresholds = state.get("adaptive_thresholds", {})
    if threshold_type in adaptive_thresholds:
        return adaptive_thresholds[threshold_type]
    
    # 否则使用默认值
    return default_thresholds.get(threshold_type, 0.7)

def update_adaptive_threshold(state: ProjectManagementState, 
                            threshold_type: str, 
                            new_value: float) -> ProjectManagementState:
    """
    更新自适应阈值
    
    Args:
        state: 项目状态
        threshold_type: 阈值类型
        new_value: 新阈值
        
    Returns:
        更新后的状态
    """
    if "adaptive_thresholds" not in state:
        state["adaptive_thresholds"] = {}
    state["adaptive_thresholds"][threshold_type] = new_value
    return state

def should_proceed_to_next_phase(state: ProjectManagementState, 
                                current_results: Dict[str, Any]) -> bool:
    """
    判断是否应该进入下一阶段
    
    Args:
        state: 项目状态
        current_results: 当前执行结果
        
    Returns:
        是否应该进入下一阶段
    """
    # 使用基于改进效果的决策逻辑
    improvement_based_decision = should_proceed_based_on_improvement(state, current_results)
    
    # 保持原有的自适应阈值逻辑作为后备
    phase = state.get("project_phase", "requirements")
    iteration_count = state.get("iteration_count", 0)
    
    # 获取阶段特定的质量标准
    quality_metrics = calculate_quality_metrics(state, current_results)
    
    # 根据阶段和迭代次数动态调整标准
    if phase == "testing":
        pass_rate = quality_metrics.get("pass_rate", 0)
        required_pass_rate = get_adaptive_threshold(state, "test_pass_rate")
        
        # 随着迭代次数增加，逐渐降低要求（但有限度）
        adjusted_threshold = max(required_pass_rate - (iteration_count * 0.05), 0.6)
        return improvement_based_decision or pass_rate >= adjusted_threshold
    
    elif phase == "development":
        code_quality = quality_metrics.get("code_quality", 0)
        required_quality = get_adaptive_threshold(state, "quality_score")
        return improvement_based_decision or code_quality >= required_quality
    
    # 其他阶段基于综合质量评估或改进效果
    overall_quality = sum(quality_metrics.values()) / max(1, len(quality_metrics))
    return improvement_based_decision or overall_quality >= 0.7

def get_feedback_based_decisions(state: ProjectManagementState) -> Dict[str, Any]:
    """
    基于反馈生成决策建议

    Args:
        state: 项目状态

    Returns:
        决策建议
    """
    feedback_history = state.get("feedback_history", [])
    recent_feedback = feedback_history[-5:] if len(feedback_history) >= 5 else feedback_history  # 最近5条反馈
    decisions = {}

    for feedback in recent_feedback:
        feedback_text = feedback.get("feedback", "").lower()
        role = feedback.get("role", "")

        # 根据反馈内容生成决策建议
        if any(keyword in feedback_text for keyword in ["bug", "error", "fix"]):
            decisions.setdefault("development", []).append("需要修复问题")

        if any(keyword in feedback_text for keyword in ["improve", "better", "enhance"]):
            decisions.setdefault("design", []).append("需要改进设计")

        if any(keyword in feedback_text for keyword in ["test", "quality", "verify"]):
            decisions.setdefault("testing", []).append("需要加强测试")

    return decisions


def evaluate_iteration_improvement(state: ProjectManagementState, previous_metrics: Dict[str, float]) -> Dict[str, Any]:
    """
    评估迭代改进效果

    Args:
        state: 当前项目状态
        previous_metrics: 上一次迭代的质量指标

    Returns:
        改进评估结果
    """
    current_metrics = state.get("quality_metrics", {})
    improvement_results = {}
    
    # 计算每个指标的改进幅度
    for metric in set(previous_metrics.keys()) | set(current_metrics.keys()):
        prev_value = previous_metrics.get(metric, 0)
        curr_value = current_metrics.get(metric, 0)
        
        if prev_value > 0:  # 避免除零错误
            improvement = (curr_value - prev_value) / prev_value
        else:
            improvement = curr_value  # 如果之前为0，改进就是当前值
            
        improvement_results[metric] = {
            "previous": prev_value,
            "current": curr_value,
            "improvement": improvement,
            "improvement_percentage": improvement * 100
        }
    
    # 计算总体改进分数
    if improvement_results:
        total_improvement = sum(result["improvement"] for result in improvement_results.values())
        avg_improvement = total_improvement / len(improvement_results)
    else:
        avg_improvement = 0
    
    improvement_results["overall"] = {
        "average_improvement": avg_improvement,
        "improvement_score": min(max(avg_improvement * 10, 0), 10)  # 归一化到0-10分
    }
    
    return improvement_results


def get_phase_specific_strategy(state: ProjectManagementState) -> Dict[str, Any]:
    """
    获取阶段特定的迭代策略

    Args:
        state: 项目状态

    Returns:
        阶段特定策略配置
    """
    from src.config.settings import settings
    
    phase = state.get("project_phase", "requirements")
    phase_strategies = settings.WORKFLOW_PHASE_SPECIFIC_STRATEGIES
    
    # 返回当前阶段的策略，如果没有配置则返回默认策略
    return phase_strategies.get(phase, {
        "focus_metrics": [],
        "improvement_threshold": 0.1,
        "max_iterations": settings.WORKFLOW_MAX_ITERATION_LIMIT
    })


def should_proceed_based_on_improvement(state: ProjectManagementState, 
                                      current_results: Dict[str, Any]) -> bool:
    """
    基于改进效果决定是否进入下一阶段

    Args:
        state: 项目状态
        current_results: 当前执行结果

    Returns:
        是否应该基于改进效果进入下一阶段
    """
    from src.config.settings import settings
    
    phase = state.get("project_phase", "requirements")
    iteration_count = state.get("iteration_count", 0)
    
    # 获取阶段特定策略
    phase_strategy = get_phase_specific_strategy(state)
    max_iterations = phase_strategy.get("max_iterations", 
                                      settings.WORKFLOW_MAX_ITERATION_LIMIT)
    
    # 检查迭代次数限制
    if iteration_count >= max_iterations:
        return True  # 达到最大迭代次数，强制推进
    
    # 计算当前质量指标
    current_metrics = calculate_quality_metrics(state, current_results)
    
    # 获取上一次迭代的质量指标（如果有）
    iteration_history = state.get("iteration_history", [])
    if len(iteration_history) >= 2:
        previous_metrics = iteration_history[-2].get("result", {}).get("quality_metrics", {})
    else:
        previous_metrics = {}
    
    # 评估改进效果
    improvement_results = evaluate_iteration_improvement(state, previous_metrics)
    improvement_score = improvement_results.get("overall", {}).get("improvement_score", 0)
    
    # 获取阶段特定的改进阈值
    improvement_threshold = phase_strategy.get("improvement_threshold", 0.1)
    required_improvement = improvement_threshold * 10  # 转换为0-10分制
    
    # 如果改进效果达到阈值，或者质量已经很高，则推进
    if improvement_score >= required_improvement:
        return True
    
    # 检查关键质量指标是否达标
    focus_metrics = phase_strategy.get("focus_metrics", [])
    if focus_metrics:
        key_metrics_ok = all(
            current_metrics.get(metric, 0) >= 0.7  # 关键指标达到70%以上
            for metric in focus_metrics
        )
        if key_metrics_ok:
            return True
    
    return False

# 辅助函数 - 质量指标计算
def _calculate_completeness(analysis: Dict[str, Any]) -> float:
    """计算需求完整性"""
    if not analysis:
        return 0.0
    
    # 简单实现：检查关键字段是否存在
    required_fields = ["functional_requirements", "non_functional_requirements", "priority_list"]
    present_fields = [field for field in required_fields if field in analysis]
    
    return len(present_fields) / len(required_fields)

def _calculate_clarity(analysis: Dict[str, Any]) -> float:
    """计算需求清晰度"""
    if not analysis:
        return 0.0
    
    # 简单实现：基于文本长度和结构
    text = str(analysis)
    score = min(len(text) / 1000, 1.0)  # 文本越长，分数越高（有限制）
    
    if "priority_list" in analysis and isinstance(analysis["priority_list"], list):
        score += 0.2
    
    return min(score, 1.0)

def _calculate_innovation(design: Dict[str, Any]) -> float:
    """计算设计创新性"""
    if not design:
        return 0.0
    
    # 简单实现：基于设计内容的独特性
    text = str(design)
    unique_words = len(set(text.split()))
    return min(unique_words / 100, 1.0)

def _calculate_usability(design: Dict[str, Any]) -> float:
    """计算设计可用性"""
    if not design:
        return 0.0
    
    # 简单实现：检查设计文档的结构完整性
    score = 0.5  # 基础分
    
    if isinstance(design, dict):
        if "wireframes" in design:
            score += 0.2
        if "interaction_flow" in design:
            score += 0.2
        if "design_system" in design:
            score += 0.1
    
    return min(score, 1.0)

def _calculate_code_quality(code: str) -> float:
    """计算代码质量"""
    if not code:
        return 0.0
    
    # 简单实现：基于代码长度和结构
    lines = code.split('\n')
    if not lines:
        return 0.0
    
    # 计算注释比例
    comment_lines = sum(1 for line in lines if line.strip().startswith('#') or line.strip().startswith('//'))
    comment_ratio = comment_lines / len(lines)
    
    # 计算函数/方法数量
    function_count = sum(1 for line in lines if 'def ' in line or 'function ' in line)
    
    score = min(comment_ratio * 0.5 + min(function_count / 10, 0.5), 1.0)
    return score

def _calculate_modularity(code: str) -> float:
    """计算代码模块化程度"""
    if not code:
        return 0.0
    
    lines = code.split('\n')
    if not lines:
        return 0.0
    
    # 计算导入语句数量（模块化指标）
    import_lines = sum(1 for line in lines if 'import ' in line or 'from ' in line)
    
    return min(import_lines / 10, 1.0)
